package com.kanshu.ksgb.fastread.doudou.common.business.ad

import android.app.Activity
import android.graphics.Color
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.inmobi.ads.InMobiAdRequestStatus
import com.inmobi.ads.InMobiInterstitial
import com.inmobi.ads.InMobiNative
import com.inmobi.ads.InMobiNative.NativeAdListener
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideImageLoader
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.*


/**
 * Title:
 * Description:
 * Copyright: Copyright(c)2018
 * Company: 看书网
 * CreateTime: 2018/5/18 11:21
 *
 * @author EvanHe
 * @version 3.0
 */
class InmobiAdUtils {


    companion object {

        private fun showSplashAd(activity: Activity, container: ViewGroup?, skipContainer: TextView?, nativeAd: InMobiNative, adListener: BaseAdListener?) {
            val adContainer = container ?: FrameLayout(activity)
            AdUtils.destroyAd(adContainer)
            adContainer.removeAllViews()
            adContainer.addView(nativeAd.getPrimaryViewOfWidth(activity.application.applicationContext, adContainer, adContainer, DisplayUtils.getScreenWidth(activity)))
            adContainer.tag = nativeAd
            adListener?.onAdLoadSucceeded(adContainer)
            adListener?.onBackAd(nativeAd)
            if (adListener is SplashAdListener) {
                adListener.isShowSkipView(true)
            }
            var time = 5
            skipContainer?.text = String.format(activity.getString(R.string.ad_click_to_skip), time)
            val timer = Timer(true)
            timer.schedule(object : TimerTask() {
                override fun run() {
                    AndroidSchedulers.mainThread().scheduleDirect {
                        time--
                        if (time == 0) {
                            adListener?.onADClosed()
                        } else {
                            skipContainer?.text = String.format(activity.getString(R.string.ad_click_to_skip), if (time > 0) time else 0)
                        }
                    }
                }
            }, 1000, 1000)
            if (adListener is SplashAdListener) {
                adListener.onFastADClosed(timer)
            }
        }

        private fun showBannerAd(activity: Activity, container: ViewGroup?, inMobiNative: InMobiNative, adConfig: ADConfigBean, adListener: BaseAdListener?) {
            val adContainer = container ?: FrameLayout(activity)
            val view = View.inflate(activity, R.layout.layout_inmobi_ad_container, null) as View
            val customBannerLayout = view.findViewById(R.id.custom_banner_layout) as RelativeLayout
            customBannerLayout.visibility = View.VISIBLE
            when (adConfig.ad_position.toInt()) {
                ADConfigBean.POSITION_BOOK_READER_BOTTOM, ADConfigBean.POSITION_BOOK_READER_BOTTOM_5 -> {
                    customBannerLayout.setBackgroundColor(Color.TRANSPARENT)
                }
                else -> {
                    customBannerLayout.setBackgroundColor(Color.WHITE)
                }
            }
            val adImg = view.findViewById(R.id.ad_img) as FrameLayout
            val title = view.findViewById(R.id.tv_ad_title) as TextView
            val desc = view.findViewById(R.id.tv_ad_desc) as TextView
            title.text = inMobiNative.adTitle
            desc.text = inMobiNative.adDescription
            adImg.removeAllViews()
            adImg.addView(inMobiNative.getPrimaryViewOfWidth(activity.application.applicationContext, adImg, adImg, DisplayUtils.dip2px(activity, 100f)))
            AdUtils.destroyAd(adContainer)
            adContainer.removeAllViews()
            adContainer.addView(view)
            view.setOnClickListener({
                inMobiNative.reportAdClickAndOpenLandingPage()
            })
            adContainer.tag = inMobiNative
            adListener?.onAdLoadSucceeded(adContainer)
            adListener?.onBackAd(inMobiNative)
        }

        /**
         * 获取3:4比例的收藏广告
         */
        private fun showAd34(activity: Activity, adContainer: ViewGroup?, inMobiNative: InMobiNative, layout: Int, adListener: BaseAdListener?) {
            val rootView = LayoutInflater.from(activity).inflate(layout, adContainer, false)
            val orginImageView: ImageView = rootView.findViewById(R.id.cover) as ImageView
            orginImageView.run { visibility = View.GONE }
            val adContainer2 = rootView.findViewById(R.id.ad_container) as FrameLayout
            val title = rootView.findViewById(R.id.book_title) as TextView?
            val desc = rootView.findViewById(R.id.desc) as TextView?
            title?.text = inMobiNative.adTitle
            desc?.text = inMobiNative.adDescription
            AdUtils.destroyAd(adContainer)
            adContainer2.removeAllViews()
            adContainer2.addView(inMobiNative.getPrimaryViewOfWidth(activity.application.applicationContext, adContainer2, adContainer2, DisplayUtils.dip2px(activity, 90f)))
            rootView.tag = inMobiNative
            adListener?.onAdLoadSucceeded(rootView)
            adListener?.onBackAd(inMobiNative)
        }

        /**
         * 获取3:2比例的章节之间广告
         */
        private fun showAd23(activity: Activity, container: ViewGroup?, inMobiNative: InMobiNative, adConfig: ADConfigBean, adListener: BaseAdListener?) {
            val adContainer = container ?: FrameLayout(activity)
            val view = View.inflate(activity, R.layout.layout_inmobi_ad_container, null) as View
            val customBannerLayout = view.findViewById(R.id.custom_chapter_ad) as RelativeLayout
            customBannerLayout.visibility = View.VISIBLE
            val adContent = view.findViewById(R.id.ad_content) as FrameLayout
            val title = view.findViewById(R.id.ad_title) as TextView
            val icon = view.findViewById(R.id.tv_ad_icon) as ImageView
            if (!TextUtils.isEmpty(inMobiNative.adTitle)) {
                title.text = inMobiNative.adTitle
                title.visibility = View.VISIBLE
            }
            GlideImageLoader.load(inMobiNative.adIconUrl, icon, GlideImageLoader.getEmptyConfig())
            adContent.removeAllViews()
            adContent.addView(inMobiNative.getPrimaryViewOfWidth(activity.application.applicationContext, adContent, adContent, DisplayUtils.getScreenWidth(activity)))
            AdUtils.destroyAd(adContainer)
            adContainer.removeAllViews()
            adContainer.addView(view)
            view.setOnClickListener({
                inMobiNative.reportAdClickAndOpenLandingPage()
            })
            adContainer.tag = inMobiNative
            adListener?.onAdLoadSucceeded(adContainer)
            adListener?.onBackAd(inMobiNative)
        }

        private var nativeAd: InMobiNative? = null
        fun fetchAd(activity: Activity, adContainer: ViewGroup?, skipContainer: TextView?, adConfig: ADConfigBean, adStyle: Int, layout: Int, adListener: BaseAdListener?) {
            val placementId: String = if (adStyle == AdStyleBean.SPLASH_STYLE) {
                if (adConfig.ad_position_id.contains(",")) {
                    val strList: List<String> = adConfig.ad_position_id.split(",")
                    if (DisplayUtils.getScreenWidth(activity).toDouble() / DisplayUtils.getScreenHeight(activity) >= 9.0 / 16) {
                        strList[0]
                    } else {
                        strList[1]
                    }
                } else {
                    adConfig.ad_position_id
                }
            } else {
                adConfig.ad_position_id
            }
            val adId: Long
            try {
                adId = placementId.toLong()
            } catch (e: Exception) {
                e.printStackTrace()
                if (adStyle != AdStyleBean.SPLASH_STYLE) {//开屏广告不需要保底广告
                    AdUtils.fetchAdFailed(activity, adContainer, adConfig, adStyle, layout, adListener)
                } else {
                    adListener?.onAdLoadFailed()
                }
                return@fetchAd
            }
            val timeout = 2500L
            var isCallBackSuccess = false
            nativeAd = InMobiNative(activity.application.applicationContext, adId, object : NativeAdListener {
                override fun onAdLoadSucceeded(p0: InMobiNative) {
                    if (!isCallBackSuccess) {
                        isCallBackSuccess = true
                        choiceAdShow(activity, adContainer, skipContainer, p0, adStyle, layout, adListener, adConfig)
                    }
                }

                override fun onAdFullScreenDismissed(p0: InMobiNative?) {
                    Log.i("inmobiAdUtils", "onAdFullScreenDismissed")
                }

                override fun onAdImpressed(p0: InMobiNative) {
                    Log.i("inmobiAdUtils", "onAdImpressed")
                }

                override fun onMediaPlaybackComplete(p0: InMobiNative) {
                    Log.i("inmobiAdUtils", "onMediaPlaybackComplete")
                }

                override fun onAdLoadFailed(p0: InMobiNative, p1: InMobiAdRequestStatus) {
                    Log.i("inmobiAdUtils", "onAdLoadFailed : ${p1.statusCode}   ${p1.message}")
                    if (!isCallBackSuccess) {
                        isCallBackSuccess = true
                        if (adStyle != AdStyleBean.SPLASH_STYLE) {
                            AdUtils.fetchAdFailed(activity, adContainer, adConfig, adStyle, layout, adListener)
                        } else {
                            adListener?.onAdLoadFailed()
                        }
                    }
                }

                override fun onUserWillLeaveApplication(p0: InMobiNative?) {
                    Log.i("inmobiAdUtils", "onUserWillLeaveApplication")
                }

                override fun onAdClicked(p0: InMobiNative) {
                    Log.i("inmobiAdUtils", "onAdClicked")
                    adListener?.onAdClicked()
                    AdUtils.pVUVAd(AdPresenter.AD_CLICK, adConfig)
                    if (adStyle != AdStyleBean.SPLASH_STYLE) {
                        AdUtils.pVUVAd(AdPresenter.AD_REQUEST, adConfig)
                        p0.destroy()
                        fetchAd(activity, adContainer, skipContainer, adConfig, adStyle, layout, adListener)
                    }
                }

                override fun onAdFullScreenDisplayed(p0: InMobiNative?) {
                    Log.i("inmobiAdUtils", "onAdFullScreenDisplayed")
                }

                override fun onUserSkippedMedia(p0: InMobiNative) {
                    Log.i("inmobiAdUtils", "onUserSkippedMedia")
                }

                override fun onAdFullScreenWillDisplay(p0: InMobiNative?) {
                    Log.i("inmobiAdUtils", "onAdFullScreenWillDisplay")
                }

                override fun onAdStatusChanged(p0: InMobiNative) {
                    Log.i("inmobiAdUtils", "onAdStatusChanged")
                }
            })
            nativeAd?.let {
                it.setDownloaderEnabled(true)
                it.load()
                val handler = Handler()
                handler.postDelayed({
                    Log.i("inmobiAdUtils", "广告是否准备好：${it.isReady}")
                    if (!isCallBackSuccess) {
                        isCallBackSuccess = true
                        if (it.isReady) {
                            choiceAdShow(activity, adContainer, skipContainer, it, adStyle, layout, adListener, adConfig)
                        } else {
                            if (adStyle != AdStyleBean.SPLASH_STYLE) {//开屏广告不需要保底广告
                                AdUtils.fetchAdFailed(activity, adContainer, adConfig, adStyle, layout, adListener)
                            } else {
                                adListener?.onAdLoadFailed()
                            }
                        }
                    }
                }, timeout)
            }
        }

        fun choiceAdShow(activity: Activity, adContainer: ViewGroup?, skipContainer: TextView?, inMobiNative: InMobiNative, adStyle: Int, layout: Int, adListener: BaseAdListener?, adConfig: ADConfigBean) {
            val content = inMobiNative.customAdContent
            Log.i("InmobiAdUtils", "onAdLoadSucceeded===" + content.toString())
            AdUtils.pVUVAd(AdPresenter.AD_SHOW, adConfig)
            when (adStyle) {
                AdStyleBean.SPLASH_STYLE -> showSplashAd(activity, adContainer, skipContainer, inMobiNative, adListener)
                AdStyleBean.BANNER_STYLE -> showBannerAd(activity, adContainer, inMobiNative, adConfig, adListener)
                AdStyleBean.BOOK_COVER_STYLE -> showAd34(activity, adContainer, inMobiNative, layout, adListener)
                AdStyleBean.IMAGE_TEXT_STYLE -> showAd23(activity, adContainer, inMobiNative, adConfig, adListener)
            }
        }

        /**
         * 加载激励和全屏视频广告
         */
        fun fetchRewardedVideoAd(activity: Activity, container: ViewGroup?, adConfig: ADConfigBean, adListener: BaseAdListener?) {
            val adContainer: ViewGroup = container ?: FrameLayout(activity)
            val interstitialADListener = object : InMobiInterstitial.InterstitialAdListener2 {
                override fun onAdDisplayFailed(ad: InMobiInterstitial?) {
                    Log.i("inMobi_video_ad", "onAdDisplayFailed")
                }

                override fun onAdInteraction(ad: InMobiInterstitial?, p1: MutableMap<Any, Any>?) {
                    Log.i("inMobi_video_ad", "onAdInteraction")

                }

                override fun onAdLoadSucceeded(ad: InMobiInterstitial?) {
                    Log.i("inMobi_video_ad", "onAdLoadSucceeded")
                    if (ad == null) {
                        return
                    }
                    adListener?.onBackAd(ad)
                }

                override fun onUserLeftApplication(ad: InMobiInterstitial?) {
                    Log.i("inMobi_video_ad", "onUserLeftApplication")
                }

                override fun onAdReceived(ad: InMobiInterstitial?) {
                    Log.i("inMobi_video_ad", "onAdReceived")
                }

                override fun onAdLoadFailed(ad: InMobiInterstitial?, status: InMobiAdRequestStatus?) {
                    Log.i("inMobi_video_ad", "onAdLoadFailed : ${status?.statusCode}   ${status?.message}")
                }

                override fun onAdDisplayed(ad: InMobiInterstitial?) {
                    Log.i("inMobi_video_ad", "onAdDisplayed")
                    AdUtils.pVUVAd(AdPresenter.AD_SHOW, adConfig)
                }

                override fun onAdWillDisplay(ad: InMobiInterstitial?) {
                    Log.i("inMobi_video_ad", "onAdWillDisplay")
                }

                override fun onAdDismissed(ad: InMobiInterstitial?) {
                    Log.i("inMobi_video_ad", "onAdDismissed")
                }

                override fun onAdRewardActionCompleted(ad: InMobiInterstitial?, rewards: MutableMap<Any, Any>?) {
                    Log.i("inMobi_video_ad", "onAdRewardActionCompleted")
                    adListener?.onAdLoadSucceeded(adContainer)
                }
            }
            //val interstitialAd = InMobiInterstitial(activity, adConfig.ad_position_id.toLong(), interstitialADListener)
            val interstitialAd = InMobiInterstitial(activity, 1531697635067L, interstitialADListener)
            interstitialAd.load()
        }
    }
}